<template>
  <div class="user">
    <el-breadcrumb separator-class="el-icon-arrow-right" class="nav">
      <el-breadcrumb-item to="/welcome"
        ><strong>首页</strong></el-breadcrumb-item
      >
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表 </el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-dialog
        ref="addForm"
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="45%"
        @close="close"
      >
        <el-form
          ref="addForm"
          :rules="rules"
          :model="addForm"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserConfirm">确 定</el-button>
        </div>
      </el-dialog>
      <!--添加对话框-->
      <el-dialog
        @close="close"
        title="编辑用户"
        :visible.sync="editDialogVisible"
        width="45%"
      >
        <el-form ref="addForm" width="45%" :model="addForm" label-width="80px">
          <el-form-item label="用户名">
            <el-input disabled v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserConfirm">确 定</el-button>
        </div>
      </el-dialog>
      <!--编辑对话框-->
      <el-dialog
        title="分配角色"
        :visible.sync="setRoleDialogVisible"
        width="50%"
      >
        <div class="roles">
          <p>当前的用户：{{ userinfo.username }}</p>
          <p>当前的角色：{{ userinfo.role_name }}</p>
          <p>
            分配新角色：
            <!-- <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option value="管理员">管理员</el-option>
              <el-option value="wapre">wapre</el-option>
            </el-select> -->
            <el-select v-model="value" placeholder="请选择">
              <el-option
                v-for="(item, index) in jueselist"
                :key="index"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="feipei">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色的对话框 -->
      <div class="header">
        <el-input
          placeholder="请输入内容"
          v-model.trim="obj.query"
          class="input-with-select"
          clearable
          @clear="serch"
        >
          <el-button
            slot="append"
            @click="getUserlist"
            icon="el-icon-search"
          ></el-button>
        </el-input>
        <el-button type="primary" @click="addUser" class="add-btn"
          >添加用户</el-button
        >
      </div>
      <!--表格-->
      <el-table
        class="table"
        border
        :data="list"
        style="width: 100%"
        max-height="500"
      >
        <el-table-column align="center" label="" width="50">
          <template slot-scope="{ $index }">
            {{ obj.pagesize * (obj.pagenum - 1) + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮编"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="change(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- slot-scope="{ row }" -->
          <template slot-scope="{ row }">
            <div class="actions">
              <el-button type="primary" @click="edit(row)">
                <i class="el-icon-edit-outline"></i
              ></el-button>
              <el-button type="danger">
                <i class="el-icon-delete" @click="del(row)"></i
              ></el-button>
              <el-button type="warning" @click="chakan(row)">
                <i class="el-icon-view"></i
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="Number(obj.pagenum)"
        :page-sizes="listarr"
        :page-size="Number(obj.pagesize)"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Number(total)"
        style="margin-top: 20px"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
import { usersApi, addusersApi, delusersApi, editusersApi, edithuakuaiApi } from '@/api/user.js'// userApi
import { rolessApi } from '@/api/rights'
export default {
  name: 'Userlist',
  data () {
    return {
      list: [],
      obj: {
        query: '',
        pagenum: '1',
        pagesize: '2'
      },
      addDialogVisible: false, // 添加用户的弹窗是否显示
      editDialogVisible: false, // 编辑对话框的弹窗是否显示
      setRoleDialogVisible: false, // 分配角色对话框
      addForm: { // 添加用户表单数据
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
      },
      listarr: [1, 2, 5, 10],
      total: '',
      id: '',
      selectedRoleId: '', // 新角色
      userinfo: '',
      feipeiId: '',
      jueselist: [],
      value: ''
    }
  },
  created () {
    // 调用获取用户列表函数
    this.getUserlist()

    //角色列表
    this.getrolessApi()
  },
  computed: {
  },
  methods: {
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.obj.pagesize = val
      this.getUserlist()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.obj.pagenum = val
      this.getUserlist()
    },
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    // 获取用户列表
    async getUserlist () {
      const res = await usersApi(this.obj)
      // console.log(res, '用户列表')
      this.list = res.data.users
      this.total = res.data.total
    },
    // 打开添加框
    addUser () {
      console.log(this.addDialogVisible)
      this.addDialogVisible = true
    },
    // 确认添加用户
    addUserConfirm () {
      // 校验表单
      this.$refs.addForm.validate(async (valid) => {
        // valid是布尔值,只要有一个条件不满足就返回false
        if (valid) {
          // console.log(1)
          await addusersApi(this.addForm)
          this.obj.pagenum = 1
          this.getUserlist()
          this.addDialogVisible = false
          // 全部满足时则做其他操作,发送请求
          // 因为async函数的返回值就是promise,所以可以用await,只有成功才跳转
        } else {
          // 不满足则提示用户输入
          this.$message.error('?')
          return false
        }
      })
    },
    // 删除用户
    del (row) {
      this.$confirm('此操作将删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await delusersApi(row.id)
        console.log(res, 898989)
        this.getUserlist()
        this.$message({
          type: 'success',
          message: res.meta.msg
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 打开编辑对话框
    edit (row) {
      // console.log(row.id)
      const newArr = JSON.parse(JSON.stringify(row))
      this.addForm = newArr
      this.editDialogVisible = true
    },
    // 编辑用户
    async editUserConfirm () {
      await editusersApi(this.addForm.id, this.addForm)
      this.editDialogVisible = false
      this.obj.pagenum = 1
      this.getUserlist()
    },
    // 关机对话框清空表单值
    close () {
      // this.$refs['ruleForm']?es6新语法,表示如果有这个方法就调用,没有则不调用
      this.$refs.ruleForm?.resetFields()
      this.addForm = {
        username: '',
        password: '',
        email: '',
        mobile: ''
      }
    },
    // 滑动框
    async change (user) {
      // console.log(user, '用户');
      const res = await edithuakuaiApi(user.id, user.mg_state)
      // console.log(res, '修改');
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 打开角色分配对话框
    chakan (row) {
      this.feipeiId = row.id
      const obj = this.list.filter(item => item.id === row.id)
      console.log(obj[0], 98989)
      this.userinfo = obj[0]
      // console.log(this.userinfo, 8989);
      this.setRoleDialogVisible = true
    },
    // 分配角色权限
    async feipei () {
      // const res = await fenpeiUser(this.feipeiId)
      this.setRoleDialogVisible = false
    },
    // 检索文本框内容
    serch () {
      console.log(this.obj.pagenum, this.obj.pagesize)
      this.obj.pagenum = '1'
      this.obj.pagesize = '2'
      this.getUserlist()
    },
    //
    async getrolessApi () {
      const res = await rolessApi()
      this.jueselist = res.data
      console.log(res, 9999);
    }
  }
}
</script>
<style lang='less'  scoped>
.header {
  display: flex;
  margin-bottom: 20px;
  .input-with-select {
    width: 420px;
    margin-right: 15px;
  }
}
.item {
  padding: 18px 0;
}
.nav {
  font-size: 12px;
  margin-bottom: 15px;
}
.table {
  font-size: 12px;
}
.actions {
  display: flex;
  button {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 43px;
    height: 28px;
  }
}
//分配角色权限
.roles {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  height: 150px;
  padding: 0;
}
</style>
